let fs = require('fs');
let path = require('path');
let _ = require('lodash');
let { writeFile, beautifyJs } = require('../file');

module.exports = function many2One(config, relative) {
  let source = config.source;
  let targets = config.targets;
  let rootRelative = '../../';
  let files = fs.readdirSync(
    path.join(__dirname, rootRelative, relative, source.path)
  );
  let sourceFiles = [],
    fileStrRet = '';
  files.forEach(r => {
    if (source.suffix && source.suffix.includes(path.extname(r))) {
      sourceFiles.push(r);
    } else if (!source.suffix) {
      sourceFiles.push(r);
    }
  });
  sourceFiles.forEach(fileName => {
    try {
      fileStrRet = '';
      let jsonArr = [];
      let data = fs.readFileSync(
        path.join(
          __dirname,
          rootRelative,
          relative,
          './',
          config.source.path,
          './',
          fileName
        )
      );
      const buf = Buffer.from(data, 'utf8');
      let fileStr = buf.toString();
      if (source.reg && source.keys) {
        let reg = source.reg,
          rep;
        // 如果有reg和keys, 遍历得到一个数组，如果没有正则，则取所有内容
        while ((rep = reg.exec(fileStr))) {
          let obj = {};
          source.keys.forEach((item, idx) => {
            obj[item] = rep[idx + 1];
          });
          jsonArr.push(obj);
        }
      } else {
        fileStrRet += fileStr;
      }
      let outStr = '';
      if (targets.render) {
        if (source.reg && source.keys) {
          outStr = _.template(targets.render)({ items: jsonArr });
        } else {
          outStr = _.template(targets.render)({ items: fileStrRet });
        }
      } else {
        if (source.reg && source.keys) {
          outStr = JSON.stringify(jsonArr);
        } else {
          outStr = fileStrRet;
        }
      }
      let outName;
      if (targets.nameFormat) {
        outName = _[targets.nameFormat](path.basename(fileName)) + targets.suffix;
      } else if(targets.suffix) {
        outName = fileName + targets.suffix;
      } else {
        outName = fileName + '.js';
      }
      writeFile(
        path.join(__dirname, rootRelative, relative, './', targets.path, './'),
        outName,
        beautifyJs(outStr)
      );
    } catch (e) {}
  });
};
